package tools;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import dbtools.TripDB;

public class TripParser {

	private final static String TAG = "TripParser";

	// TODOf
	// Constructor
	public TripParser() {

	}

	public TripParser(Context applicationContext) {
		TripDB dbHandler = new TripDB(applicationContext);
		SQLiteDatabase db1 = null;
		dbHandler.onUpgrade(db1, 1, 1);
	}

	/**
	 * Getting XML from URL making HTTP Request
	 * 
	 * @param string
	 * 
	 * @return ArrayList<ArrayList<HashMap<String, String>>>
	 */
	public ArrayList<ArrayList<HashMap<String, String>>> getTripList(
			String paramUrl) {
		ArrayList<ArrayList<HashMap<String, String>>> tripList 
		= new ArrayList<ArrayList<HashMap<String, String>>>();

		URL url;
		try {
			url = new URL(paramUrl);

			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) { // Check
																// connection.
				InputStream in = httpConnection.getInputStream();

				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();

				// Parse the Trip feed.
				Document dom = db.parse(in);
				Element docEle = dom.getDocumentElement();

				// Get a list of each Trip entry.
				NodeList nl = docEle.getElementsByTagName("Trip");
				if (nl != null && nl.getLength() > 0) {
					for (int i = 0; i < nl.getLength(); i++) {
						ArrayList<HashMap<String, String>> legList 
						= new ArrayList<HashMap<String, String>>();
						int tripId = i;

						NodeList nl2 = nl.item(i).getChildNodes();
						Log.d(TAG,
								"\n********************************\nTrip id: "
										+ tripId);
						double legId = 0;
						for (int j = 0; j < nl2.getLength() - 1; j = j + 2) {

							Element legElem = (Element) nl2.item(j).getNextSibling();
							Element originElem = (Element) legElem.getElementsByTagName("Origin").item(0);
							Element destElem = (Element) legElem.getElementsByTagName("Destination").item(0);
							Element notesElem = (Element) legElem.getElementsByTagName("Notes").item(0);
							Element journeyDetElem = (Element) legElem.getElementsByTagName("JourneyDetailRef").item(0);

							String journeyDetailRef = null;
							try {
								journeyDetailRef = journeyDetElem
										.getAttribute("ref");
							} catch (Exception e) {
								Log.d(TAG, "JourneDetailRef is empty!");
							}

							HashMap<String, String> values = new HashMap<String, String>();

							int legIdInt = (int) legId;
							values.put("legId", String.valueOf(legIdInt));
							values.put("tripId", String.valueOf(tripId));
							values.put("legName", legElem.getAttribute("name"));
							values.put("legType", legElem.getAttribute("type"));
							values.put("originName", originElem.getAttribute("name"));
							values.put("originType", originElem.getAttribute("type"));
							values.put("originTime", originElem.getAttribute("time"));
							values.put("originDate", originElem.getAttribute("date"));
							values.put("destinationName", destElem.getAttribute("name"));
							values.put("destinationType", destElem.getAttribute("type"));
							values.put("destinationTime", destElem.getAttribute("time"));
							values.put("destinationDate", destElem.getAttribute("date"));
							values.put("notesText", notesElem.getAttribute("text"));
							values.put("journeyDetailRef", journeyDetailRef);

							legList.add(values);

							logCat(legId, legElem, originElem, destElem,
									notesElem, journeyDetailRef);
							legId = legId + 0.5;
						}
						tripList.add(legList);
					}
				}
			}
		} catch (MalformedURLException e) {
			Log.d(TAG, "MalformedURLException");
		} catch (IOException e) {
			Log.d(TAG, "IOException");
		} catch (ParserConfigurationException e) {
			Log.d(TAG, "Parser Configuration Exception");
		} catch (SAXException e) {
			Log.d(TAG, "SAX Exception");
		}
		return tripList;
	}

	private void logCat(double legId, Element legElem, Element originElem,
			Element destElem, Element notesElem, String journeyDetailRef) {
		Log.d(TAG, "Leg id: " + legId + "\n<Leg Name=\""
				+ legElem.getAttribute("name") + "\" type=\"" + legElem.getAttribute("type")
				+ "\">\n<Origin name=" + originElem.getAttribute("name")
				+ "\" type=\"" + originElem.getAttribute("type") + "\" time="
				+ originElem.getAttribute("time") + "\" date=" + originElem.getAttribute("date")
				+ "/>\n<Destination name="
				+ destElem.getAttribute("name") + "\" type="
				+ destElem.getAttribute("type") + "\" time="
				+ destElem.getAttribute("time") + "\" date="
				+ destElem.getAttribute("date") + "\"/>\n<Notes text="
				+ notesElem.getAttribute("text")
				+ "\"/>\n<JourneyDetailRef ref="
				+ journeyDetailRef + "\"/>\n</Leg>");
	}
}
